import 'dart:convert';

import 'package:city_pickers/city_pickers.dart';
import 'package:city_pickers/modal/result.dart';
import 'package:common_utils/common_utils.dart';
import 'package:fluro/fluro.dart';
import 'package:flutter/material.dart';
import 'package:flutter_easyloading/flutter_easyloading.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:flutter_switch/flutter_switch.dart';
import 'package:taonile/config/config.dart';

import '../http/api.dart';
import '../routers/routers.dart';
import '../views/dialog_manager.dart';

///
/// 添加/修改收货地址
///
class MineAddressEdit extends StatefulWidget {
  var receiptId = '';

  MineAddressEdit({Key? key, this.receiptId = ''}) : super(key: key);

  @override
  State<MineAddressEdit> createState() => _MineAddressEditState();
}

class _MineAddressEditState extends State<MineAddressEdit> {
  var _name = '';
  var _phone = '';
  var _area = '点击选择省市区';
  var _address = '';
  var province = '';
  var city = '';
  var area = '';
  var province_name = '';
  var city_name = '';
  var area_name = '';
  bool _isCheck = false;

  @override
  void initState() {
    super.initState();
    if (widget.receiptId.isNotEmpty) {
      getReceiptDetal();
    }
  }

  addReceipt() async {
    FocusManager.instance.primaryFocus?.unfocus();
    if (_name.isEmpty) {
      EasyLoading.showToast("请输入收货人");
      return;
    }
    if (_phone.length < 11) {
      EasyLoading.showToast("请输入正确的手机号");
      return;
    }
    if (_area.length <= 7) {
      EasyLoading.showToast("请选择省市区");
      return;
    }
    if (_address.length < 5) {
      EasyLoading.showToast("请填写详细地址，不少于5个字");
      return;
    }
    var param = {
      'mobile': _phone,
      'username': _name,
      'detail': _address,
      'province': province,
      'city': city,
      'area': area,
      'province_name': province_name,
      'city_name': city_name,
      'area_name': area_name,
      'is_default': _isCheck ? '1' : '0',
    };

    if (widget.receiptId.isNotEmpty) {
      param['id'] = widget.receiptId;
      dynamic result = await Api.upReceipt(param);
      var jsonResult = jsonDecode(jsonEncode(result));
      if (jsonResult['code'] == 1) {
        EasyLoading.showToast("修改成功");
        Routes.router.pop(context, {'result': 1});
      }
    } else {
      dynamic result = await Api.addReceipt(param);
      var jsonResult = jsonDecode(jsonEncode(result));
      if (jsonResult['code'] == 1) {
        EasyLoading.showToast("添加成功");
        Routes.router.pop(context, {'result': 1});
      }
    }
  }

  getReceiptDetal() async {
    dynamic result = await Api.receiptDetail("/${widget.receiptId}");
    var jsonResult = jsonDecode(jsonEncode(result));
    if (jsonResult['code'] == 1) {
      // LogUtil.v(jsonResult['data']['username']);
      // LogUtil.v(jsonResult['data']['mobile']);
      setState(() {
        _name = jsonResult['data']['username'];
        _phone = jsonResult['data']['mobile'];
        _area =
            '${jsonResult['data']['province_name']}-${jsonResult['data']['city_name']}-${jsonResult['data']['area_name']}';
        _address = jsonResult['data']['detail'];
        _isCheck = jsonResult['data']['is_default'].toString() == '1' ? true : false;
        province = jsonResult['data']['province'];
        city = jsonResult['data']['city'];
        area = jsonResult['data']['area'];
      });
    }
  }

  deleteReceipt() async {
    dynamic result = await Api.delReceipt({'id': widget.receiptId});
    var jsonResult = jsonDecode(jsonEncode(result));
    if (jsonResult['code'] == 1) {
      EasyLoading.showToast("删除成功");
      Routes.router.pop(context, {'result': 1});
    }
  }

  ///
  /// 弹出省市区三级选择器
  ///
  getCityResult() async {
    // type 1
    Result? result = await CityPickers.showCityPicker(
      context: context,
      height: 600.w,
      barrierOpacity: 0.5,
      theme: Theme.of(context).copyWith(),
    );
    if (result != null) {
      String str = '${result.provinceName}-${result.cityName}-${result.areaName}';
      province_name = result.provinceName!;
      city_name = result.cityName!;
      area_name = result.areaName!;
      province = result.provinceId!;
      city = result.cityId!;
      area = result.areaId!;
      setState(() {
        _area = str;
      });
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
        backgroundColor: Config.colorBg2,
        appBar: AppBar(
          title: Text(widget.receiptId.isEmpty ? '添加收货地址' : '修改收货地址'),
          centerTitle: true,
        ),
        body: SizedBox(
          width: double.infinity,
          height: double.infinity,
          child: Container(
            width: double.infinity,
            height: double.infinity,
            margin: EdgeInsets.symmetric(vertical: 25.w, horizontal: 25.w),
            child: Column(
              children: [
                Container(
                  width: double.infinity,
                  padding: EdgeInsets.symmetric(vertical: 20.w, horizontal: 20.w),
                  decoration: BoxDecoration(
                    color: (Config.colorWhite),
                    borderRadius: BorderRadius.circular(10.w),
                  ),
                  child: Column(
                    children: [
                      Row(
                        crossAxisAlignment: CrossAxisAlignment.center,
                        children: [
                          Container(
                            margin: EdgeInsets.symmetric(vertical: 5.w),
                            width: 110.w,
                            child: Text(
                              "收货人",
                              style: TextStyle(fontSize: 25.sp),
                            ),
                          ),
                          Padding(
                            padding: EdgeInsets.only(left: 30.w),
                          ),
                          Container(
                            width: 520.w,
                            margin: EdgeInsets.symmetric(vertical: 5.w),
                            child: TextField(
                              keyboardType: TextInputType.text,
                              textAlign: TextAlign.justify,
                              obscureText: false,
                              maxLength: 20,
                              maxLines: 1,
                              onChanged: (value) {
                                setState(() {
                                  _name = value;
                                });
                              },
                              style: TextStyle(fontSize: 25.sp, color: Config.colorText1),
                              decoration: const InputDecoration(
                                hintStyle: TextStyle(color: Config.colorText3),
                                hintText: "请输入收货人姓名",
                                counterText: '',
                                isDense: true,
                                border: InputBorder.none,
                                contentPadding: EdgeInsets.zero, //设置文本内容的Padding
                              ),
                              controller: TextEditingController.fromValue(
                                TextEditingValue(
                                  text: _name,
                                  selection: TextSelection.fromPosition(
                                    TextPosition(
                                        // affinity: TextAffinity.downstream,
                                        offset: _name.length),
                                  ),
                                ),
                              ),
                            ),
                          ),
                        ],
                      ),
                      Divider(
                        color: Config.colorDivider,
                        height: 40.w,
                        thickness: 2.w,
                      ),
                      Row(
                        crossAxisAlignment: CrossAxisAlignment.center,
                        children: [
                          Container(
                            margin: EdgeInsets.symmetric(vertical: 5.w),
                            width: 110.w,
                            child: Text(
                              "联系电话",
                              style: TextStyle(fontSize: 25.sp),
                            ),
                          ),
                          Padding(
                            padding: EdgeInsets.only(left: 30.w),
                          ),
                          Container(
                            width: 520.w,
                            margin: EdgeInsets.symmetric(vertical: 5.w),
                            child: TextField(
                              keyboardType: TextInputType.phone,
                              textAlign: TextAlign.justify,
                              obscureText: false,
                              maxLength: 11,
                              maxLines: 1,
                              onChanged: (value) {
                                setState(() {
                                  _phone = value;
                                });
                              },
                              style: TextStyle(fontSize: 25.sp, color: Config.colorText1),
                              decoration: const InputDecoration(
                                hintStyle: TextStyle(color: Config.colorText3),
                                hintText: "请输入收货人联系电话",
                                counterText: '',
                                isDense: true,
                                border: InputBorder.none,
                                contentPadding: EdgeInsets.zero, //设置文本内容的Padding
                              ),
                              controller: TextEditingController.fromValue(
                                TextEditingValue(
                                  text: _phone,
                                  selection: TextSelection.fromPosition(
                                    TextPosition(
                                        // affinity: TextAffinity.downstream,
                                        offset: _phone.length),
                                  ),
                                ),
                              ),
                            ),
                          ),
                        ],
                      ),
                      Divider(
                        color: Config.colorDivider,
                        height: 40.w,
                        thickness: 2.w,
                      ),
                      Row(
                        crossAxisAlignment: CrossAxisAlignment.center,
                        children: [
                          Container(
                            margin: EdgeInsets.symmetric(vertical: 5.w),
                            width: 110.w,
                            child: Text(
                              "所在地区",
                              style: TextStyle(fontSize: 25.sp),
                            ),
                          ),
                          Padding(
                            padding: EdgeInsets.only(left: 30.w),
                          ),
                          InkWell(
                            onTap: () {
                              getCityResult();
                            },
                            child: Container(
                              width: 490.w,
                              margin: EdgeInsets.symmetric(vertical: 5.w),
                              child: Text(
                                _area,
                                style: TextStyle(fontSize: 25.sp),
                              ),
                            ),
                          ),
                          Icon(
                            Icons.arrow_forward_ios,
                            size: 25.w,
                          ),
                        ],
                      ),
                      Divider(
                        color: Config.colorDivider,
                        height: 40.w,
                        thickness: 2.w,
                      ),
                      Row(
                        crossAxisAlignment: CrossAxisAlignment.center,
                        children: [
                          Container(
                            margin: EdgeInsets.symmetric(vertical: 5.w),
                            width: 110.w,
                            child: Text(
                              "详细地址",
                              style: TextStyle(fontSize: 25.sp),
                            ),
                          ),
                          Padding(
                            padding: EdgeInsets.only(left: 30.w),
                          ),
                          Container(
                            width: 520.w,
                            margin: EdgeInsets.symmetric(vertical: 5.w),
                            child: TextField(
                              keyboardType: TextInputType.text,
                              textAlign: TextAlign.justify,
                              obscureText: false,
                              maxLength: 100,
                              maxLines: 1,
                              onChanged: (value) {
                                setState(() {
                                  _address = value;
                                });
                              },
                              style: TextStyle(fontSize: 25.sp, color: Config.colorText1),
                              decoration: const InputDecoration(
                                hintStyle: TextStyle(color: Config.colorText3),
                                hintText: "请填写详细地址，不少于5个字",
                                counterText: '',
                                isDense: true,
                                border: InputBorder.none,
                                contentPadding: EdgeInsets.zero, //设置文本内容的Padding
                              ),
                              controller: TextEditingController.fromValue(
                                TextEditingValue(
                                  text: _address,
                                  selection: TextSelection.fromPosition(
                                    TextPosition(
                                        // affinity: TextAffinity.downstream,
                                        offset: _address.length),
                                  ),
                                ),
                              ),
                            ),
                          ),
                        ],
                      ),
                    ],
                  ),
                ),
                Container(
                  width: double.infinity,
                  margin: EdgeInsets.only(top: 25.w),
                  padding: EdgeInsets.symmetric(vertical: 20.w, horizontal: 20.w),
                  decoration: BoxDecoration(
                    color: (Config.colorWhite),
                    borderRadius: BorderRadius.circular(10.w),
                  ),
                  child: Column(
                    children: [
                      Row(
                        crossAxisAlignment: CrossAxisAlignment.center,
                        mainAxisAlignment: MainAxisAlignment.spaceBetween,
                        children: [
                          Container(
                            margin: EdgeInsets.symmetric(vertical: 5.w),
                            child: Text(
                              "设为默认地址",
                              style: TextStyle(fontSize: 25.sp),
                            ),
                          ),
                          FlutterSwitch(
                            width: 96.w,
                            height: 44.w,
                            activeColor: Config.colorMain,
                            valueFontSize: 15.sp,
                            toggleSize: 38.w,
                            value: _isCheck,
                            borderRadius: 22.w,
                            padding: 5.w,
                            showOnOff: true,
                            onToggle: (val) {
                              setState(() {
                                _isCheck = val;
                              });
                            },
                          ),
                        ],
                      ),
                      Visibility(
                        visible: widget.receiptId.isNotEmpty,
                        child: Divider(
                          color: Config.colorDivider,
                          height: 40.w,
                          thickness: 2.w,
                        ),
                      ),
                      Visibility(
                        visible: widget.receiptId.isNotEmpty,
                        child: Row(
                          crossAxisAlignment: CrossAxisAlignment.center,
                          mainAxisAlignment: MainAxisAlignment.spaceBetween,
                          children: [
                            InkWell(
                              child: Container(
                                margin: EdgeInsets.symmetric(vertical: 5.w),
                                child: Text(
                                  "删除地址",
                                  style: TextStyle(fontSize: 25.sp, color: Colors.red),
                                ),
                              ),
                              onTap: () {
                                DialogManager.showDefaultDialog(context, "确认删除地址", () {
                                  deleteReceipt();
                                });
                              },
                            ),
                          ],
                        ),
                      ),
                    ],
                  ),
                ),
                Container(
                  width: 750.w,
                  height: 100.w,
                  padding: EdgeInsets.symmetric(vertical: 8.w, horizontal: 8.w),
                  margin: EdgeInsets.only(top: 45.w),
                  child: ElevatedButton(
                    clipBehavior: Clip.antiAlias,
                    onPressed: () => {addReceipt()},
                    style: ElevatedButton.styleFrom(shape: const StadiumBorder()),
                    child: const Text('保存'),
                  ),
                ),
              ],
            ),
          ),
        ));
  }
}
